package com.chap5_2;

/**
 * <p>
 * <code>NormalDeadLock</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-28 9:57
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class SafeOperate {
    private static Object No13 = new Object();
    private static Object No14 = new Object();
    private static Object tieLock = new Object();

    private static void method(Object first,Object second) throws InterruptedException {
        String name = Thread.currentThread().getName();

        int firstHash = System.identityHashCode(first);
        int secondHash = System.identityHashCode(second);
        if (firstHash<secondHash){
            synchronized (first){
                System.out.println(name+" get first");
                Thread.sleep(100);
                synchronized (second){
                    System.out.println(name+" get second");
                }
            }
        }else if (secondHash<firstHash){
            synchronized (second){
                System.out.println(name+" get first");
                Thread.sleep(100);
                synchronized (first){
                    System.out.println(name+" get second");
                }
            }
        }else {
            synchronized (tieLock){
                synchronized (first){
                    System.out.println(name+" get first");
                    Thread.sleep(100);
                    synchronized (second){
                        System.out.println(name+" get second");
                    }
                }
            }
        }
    }



    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    method(No13,No14);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"张三").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    method(No14,No13);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"李四").start();
    }
}
